#include "ccarRequestPassenger.h"
#include <QDataStream>
#include <QTcpSocket>
#include "protocol/CarRequestPassenger.h"
#include "protocol/srvCarRequestPassengersAnsToCar.h"

CCarRequestPassengers::CCarRequestPassengers(QObject *parent)
    :INetWorking(parent)
{
}

CCarRequestPassengers::~CCarRequestPassengers()
{
}

void CCarRequestPassengers::prepareWriteData(QByteArray* block, void* param)
{
    // we cannot discrete this definition to the outside of the block,
    // and pass the reference to the funtion, or it will cause some
    // unknown problems, such as wrong streams. Maybe it is a bug of QT.
    QDataStream out(block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_3);


    protocal::CarRequestPassenger* pRequestPassenger = (protocal::CarRequestPassenger*)param;

    // output the head information
    out << (qint32)(pRequestPassenger->source) \
        << (qint32)(pRequestPassenger->car_command) \
        << (qint32)(pRequestPassenger->size);

    // output the body information

    char * temp = new char [10];
    // we must do so, because the constructor of QString(char*) will truncate the
    // remaining space after '\0', and we need them to occupy the space.
    memcpy(temp, pRequestPassenger->carID, 10);
    out << QString(temp);

    delete [] temp;
}

bool CCarRequestPassengers::prepareReadData(QTcpSocket *pTcpSocket, protocal::BasePtc *basePtc)
{
    QDataStream in(pTcpSocket);

    if (   basePtc->source != protocal::SERVER\
        || basePtc->car_command != protocal::SRV_CAR_REQUEST_PASSENGERS
        || basePtc->size != sizeof(protocal::SrvCarQequestPassengersAnsToCar))
    {
        return false;
    }

    // recieve data, from srvCarRequestPassengersAnsToCar.h
    char* temp = new char [10];
    in >> temp;
    client_id = QString(temp);
    in >> temp;
    client_name = QString(temp);
    in >> arrivingTime;

    // GPS information should be accepted here
    in >> startPos.lat;
    in >> startPos.lon;

    in >> endPos.lat;
    in >> endPos.lon;

    delete [] temp;

    //in
    char *temp2 = new char [12];
    in >> temp2;
    mobile_phone = QString(temp2);
    delete [] temp2;

    formResult();

    return true;
}

void CCarRequestPassengers::formResult()
{
    resultMap.insert(QString("client_id"), client_id);
    resultMap.insert(QString("client_name"), client_name);
    resultMap.insert(QString("arrivingTime"), QString::number(arrivingTime));

    resultMap.insert(QString("startGPS.lat"), QString::number(startPos.lat));
    resultMap.insert(QString("startGPS.lon"), QString::number(startPos.lon));

    resultMap.insert(QString("endGPS.lat"), QString::number(endPos.lat));
    resultMap.insert(QString("endGPS.lon"), QString::number(endPos.lon));

    resultMap.insert(QString("mobile_phone"), mobile_phone );
}
